﻿using Svg;
using System;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Yz.Core.Tools;

namespace Yz.Mvc.Controllers
{
    public class SvgController : BaseController
    {    /// <summary>
         ///     保存svg到image中
         /// </summary>
         /// <returns></returns>
        [HttpPost]
        public JsonResult SaveSvgToImage()
        {
            var tSvg = HttpUtility.HtmlDecode(Request.Form["strsvg"]);
            var fileTempPath = base.TempFileRootPath;

            var localPath = Server.MapPath("~" + fileTempPath);
            if (!Directory.Exists(localPath))
            {
                Directory.CreateDirectory(localPath);
            }
            var fileName = Guid.NewGuid().ToString().Replace("-", "") + ".png";
            var tData = new MemoryStream(Encoding.UTF8.GetBytes(tSvg));
            var tStream = new MemoryStream();
            try
            {
                var svgDoc = SvgDocument.Open<SvgDocument>(tData);
                svgDoc.Draw().Save(tStream, ImageFormat.Png);
                //将二进制流保存为指定路径下的具体文件
                System.IO.File.WriteAllBytes(localPath + fileName, tStream.ToArray());
                return Json(new { res = true, msg = "转换成功！", filePath = fileTempPath + fileName });
            }
            catch (Exception ex)
            {
                YzNLog.Error(ex);
                return Json(new { res = false, msg = "转换失败！" });
            }
            finally
            {
                tStream.Dispose();
                tStream.Close();
                tData.Dispose();
                tData.Close();
            }
        }
    }
}
